package com.scitc.pleasurevideo.x5webview;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.scitc.pleasurevideo.data.ETMan;
import com.scitc.pleasurevideo.data.SystemSettingDataMan;
import com.scitc.pleasurevideo.datasql.VideoSourceSqlData;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.okgoutil.HttpCompleteOrFail;
import com.scitc.pleasurevideo.okgoutil.OkGoUtil;
import com.scitc.pleasurevideo.pojo.VideoSourceVo;
import com.scitc.pleasurevideo.util.AtyContainer;
import com.scitc.pleasurevideo.util.ConstUtil;
import com.tencent.smtt.sdk.QbSdk;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MyApplication extends Application {
    private static Application instance;
    private static String loginString="";
    private static int playTimeSecond=0;
    public static boolean isShowDownloadUi=true;
    private Handler handler = new Handler();

    private Timer timer;

    /**
     * 当前处于前台的activity数量
     */
    private int foregroundActivityCount = 0;
    @Override
    public void onCreate() {
        super.onCreate();
        initSplash();
//        initX5WebView();
        initConfig(this);
        initData();
        bindTimer();
    }


    /**
     * 当有activity打开的时候
     */
    private void initSplash() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityStopped(Activity activity) {
                Log.v("plesurevideo", activity + "onActivityStopped");
                foregroundActivityCount--;
                if(foregroundActivityCount==0){
                    saveDataToDay();
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.v("plesurevideo", activity + "onActivityStarted");
                foregroundActivityCount++;
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                Log.v("plesurevideo", activity + "onActivitySaveInstanceState");
            }

            @Override
            public void onActivityResumed(Activity activity) {
                Log.v("plesurevideo", activity + "onActivityResumed");
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.v("plesurevideo", activity + "onActivityPaused");
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.v("plesurevideo", activity + "onActivityDestroyed");
                AtyContainer.getInstance().removeActivity(activity);
            }

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.v("plesurevideo", activity + "onActivityCreated");
                AtyContainer.getInstance().addActivity(activity);
            }
        });

    }


    /**
     * 加载视频网址数据
     */
    private void initData() {
        //加载视频播放网址列表
        OkGoUtil.init().getVideoSourceList(new HttpCompleteOrFail() {
            @Override
            public void onComplete(String json) {
                try {
                    List<VideoSourceVo> videoSourceVos= new Gson().fromJson(json, new TypeToken<List<VideoSourceVo>>(){}.getType());
                    if(videoSourceVos==null||videoSourceVos.size()<1) {
                        return;
                    }
                    VideoSourceSqlData.getDbDataManager().saveAllVideoSourceFrist(videoSourceVos);
                } catch (JsonSyntaxException e) { }
            }

            @Override
            public void onFile(String information) {

            }
        });

        ETMan.savePref(getInstance(),ConstUtil.IS_SHOW_DOWNLOAD_UI,false);
        isShowDownloadUi=ETMan.getPref(getInstance(),ConstUtil.IS_SHOW_DOWNLOAD_UI,false);
    }

    /**
     * 处理定时任务关闭
     */
    public void bindTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        handlerSettingExitTime();
                    }
                });
            }
        }, 0, 3000);
    }
    /**
     *  处理定时任务关闭
     */
    private void handlerSettingExitTime() {
        boolean isClose = SystemSettingDataMan.getDataMan().isShouldClose();
        if (isClose) {
            SystemSettingDataMan.getDataMan().closeApp();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AtyContainer.getInstance().finishAllActivity();
                }
            }, 1000);
        }
    }

    /**
     * 存储今天的播放时长
     */
    private void saveDataToDay(){
        ETMan.savePref(getInstance(), ConstUtil.APP_PLAY_TIME_SECOND_TODAY,getPlayTimeSecond());
        ETMan.savePref(getInstance(), ConstUtil.APP_PLAY_TIME_SECOND_ALL,ETMan.getPref(getInstance(),ConstUtil.APP_PLAY_TIME_SECOND_ALL,0)+getPlayTimeSecond());
        setPlayTimeSecond(0);
    }

    private void initX5WebView() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                if (arg0) {
                    Log.e("=====myApp", " x5WebView内核加载成功" + arg0);
                } else {
                    Log.e("=====myApp", " x5WebView内核加载失败" + arg0);
                }
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }
    public static void initConfig(final Application _instance) { instance = _instance; }
	public static Application getInstance() { return instance; }

    public static String getLoginString() { return loginString; }
    public static void setLoginString(String loginString) { MyApplication.loginString = loginString; }

    public static int getPlayTimeSecond() { return playTimeSecond; }
    public static void setPlayTimeSecond(int playTimeSecond) { MyApplication.playTimeSecond = playTimeSecond; }
    public static void setPlayTimeSecondAdd() { MyApplication.playTimeSecond = MyApplication.playTimeSecond+1; }
}
